<template>
  <div class="box-container flex-row row-between">
    <div class="left-tree">
      <Treeselect
        @treeSelect="treeSelect"
        :data="g6Tree && JSON.stringify(g6Tree) != '{}' ? [g6Tree] : []"
      />
    </div>
    <div class="right-box">
      <div class="right-top">
        <div class="flexAlign">
          <myButton
            :obj="{
              title: '本地指标体系导入',
              img: require('@/assets/images/dao1.png'),
            }"
            @btnClick="importByLocal"
          ></myButton>
          <myButton
            :obj="{
              title: '历史指标体系导入',
              img: require('@/assets/images/dao1.png'),
            }"
            @btnClick="importByHistoryOrTmp(1)"
          ></myButton>
          <myButton
            :obj="{
              title: '暂存模型导入',
              img: require('@/assets/images/dao1.png'),
            }"
            @btnClick="importByHistoryOrTmp(2)"
          ></myButton>
          <myButton
            :obj="{
              title: '新建指标体系',
              icon: 'el-icon-plus',
            }"
            @btnClick="newSystem"
          ></myButton>
        </div>
        <div class="flexAlign">
          <myButton
            :obj="{
              title: '指标体系模板下载',
              img: require('@/assets/images/xiaz.png'),
            }"
            class="download-btn"
            @btnClick="downloadTemplet"
          ></myButton>
        </div>
      </div>
      <div class="right-middle">
        <TitleAndContent
          :obj="{
            title: '指标体系编辑',
            img: require('@/assets/myself_img/icon_editor.png'),
          }"
        >
          <!-- <div class="graph" id="mountNode"></div> -->
          <g6-container
            v-if="g6Tree && JSON.stringify(g6Tree) != '{}'"
            class="graph"
            :treedata="g6CmpData"
            :numInput="true"
            :operate="true"
            @updateTree="updateG6Tree"
            @deleteTree="deleteTree"
            @addTree="addG6Tree"
          ></g6-container>
        </TitleAndContent>
      </div>
      <div class="right-bottom">
        <TitleAndContent
          :obj="{
            title: '指标体系描述',
            img: require('@/assets/myself_img/icon_save.png'),
          }"
        >
          <el-form
            label-width="120px"
            :inline="true"
            ref="addForm"
            :model="form"
            :rules="rules"
          >
            <el-form-item prop="name" label="指标体系名称">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item prop="type" label="指标体系类型">
              <el-select v-model="form.type">
                <el-option label="类型一" value="类型一"></el-option>
                <el-option label="类型二" value="类型二"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="content" label="指标体系简介">
              <el-input type="textarea" v-model="form.content"></el-input>
            </el-form-item>
          </el-form>
        </TitleAndContent>
      </div>
      <div class="right-footer">
        <myButton
          :obj="{
            title: '暂存',
            img: require('@/assets/myself_img/icon_save2.png'),
          }"
          class="save-btn"
          @btnClick="saveBbtnClick(1)"
        ></myButton>
        <myButton
          :obj="{
            title: '发布',
            img: require('@/assets/myself_img/icon_save3.png'),
          }"
          class="save-btn"
          @btnClick="saveBbtnClick(2)"
        ></myButton>
      </div>
    </div>

    <el-upload
      v-show="false"
      class="upload"
      :limit="1"
      :multiple="false"
      :file-list="fileList"
      accept=".xlsx,.xls"
      :drag="true"
      :auto-upload="false"
      :on-change="upload"
      action=""
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text" ref="upload">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <div class="el-upload__tip" slot="tip">
        只能上传xlsx/xls文件，且不超过500kb
      </div>
    </el-upload>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="importDialog"
      :before-close="handleClose"
    >
      <el-form
        ref="historyForm"
        :inline="true"
        size="mini"
        :model="formInline"
        class="demo-form-inline"
        style="display: flex; justify-content: space-between"
      >
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="formInline.createTime"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="formInline.type" placeholder="类型" clearable>
            <el-option label="类型一" value="shanghai"></el-option>
            <el-option label="类型二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指标体系名称" prop="name">
          <el-input
            v-model="formInline.name"
            placeholder="指标体系名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchBtn">
            <img
              :src="require('../../../assets/images/cha3.png')"
              alt=""
              srcset=""
            />
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="historyList"
        border
        stripe
        size="mini"
        @row-click="rowClick"
        show-overflow-tooltip
        highlight-current-row
        v-loading="historyListLoading"
      >
        <el-table-column label="选择" width="55" align="center">
          <template slot-scope="scope">
            <el-radio :label="scope.row.id" v-model="selectHistoryId">
              {{ "" }}
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column type="index" align="center" label="序号" width="60">
        </el-table-column>
        <el-table-column prop="name" label="指标体系名称"> </el-table-column>
        <el-table-column prop="type" align="center" label="指标体系类型">
        </el-table-column>
        <el-table-column
          prop="updateTime"
          align="center"
          label="创建时间"
          width="150"
        >
        </el-table-column>
        <el-table-column prop="createBy" label="创建人员"> </el-table-column>
        <!-- <el-table-column
          prop="content"
          align="center"
          label="指标体系详情"
          width="120"
        >
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="getDetail"
              type="text"
              size="small"
            >
              <img
                :src="require('../../../assets/images/xiug.png')"
                alt=""
                srcset=""
              />
              设置
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="historyTotal"
        :current-page="historyCurrPage"
        @current-change="changeHistoryPage"
        style="text-align: right"
      >
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleClose">取 消</el-button>
        <el-button
          size="mini"
          :disabled="!selectHistoryId"
          type="primary"
          @click="commitImport"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Treeselect from "@/components/myselfCom/systemTree";
import TitleAndContent from "@/components/myselfCom/titleAndContent";
import myButton from "@/components/myselfCom/myButton";
import TableCom from "@/components/myselfCom/tableCom.vue";
import G6Container from "@/components/G6Container/index";
import {
  getTreeByExcel,
  addSystem,
  queryById,
  queryNewById,
  getHistoryList,
  editSystem,
  downloadTemp,
} from "@/api/systemModeling.js";
export default {
  name: "",
  components: { Treeselect, TitleAndContent, myButton, G6Container },
  props: {
    data: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      importFlag: true, // true为可以导入
      fileList: [],
      g6Tree: {},
      targetData: null,
      g6CmpData: {},
      newTreeData: {
        code: null,
        id: "",
        isBottom: null,
        isId: null,
        label: "xx指标体系",
        level: null,
        num: "0",
        pid: null,
        size: [120, 50],
        sort: null,
        children: [],
      },
      form: {
        name: "",
        type: "",
        content: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入指标体系名称", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择指标体系类型", trigger: "blur" },
        ],
      },
      btnType: "",
      // 导入弹窗
      importDialog: false,
      dialogTitle: "",
      historyListLoading: false,
      formInline: {
        createTime: ["", ""],
        type: "",
        name: "",
      },
      historyList: [],
      selectHistoryId: "",
      historyCurrPage: 1,
      historyTotal: 0,
      editId: "", // 当前编辑的体系id
    };
  },
  methods: {
    treeSelect(e) {
      // console.log(e);
      this.targetData = e;
      this.g6CmpData = e;

      // this.$emit("treeSelect", e);
      // e.label = "ddfad"
    },
    // 本地导入
    importByLocal() {
      this.btnType = "local";
      // 判断当前编辑区域是否有内容
      if (!this.importFlag) {
        this.$confirm("当前编辑区内容尚未保存，是否继续导入", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 清空
          this.fileList = [];
          this.$refs.upload.click();
        });
      } else {
        // 清空
        this.fileList = [];
        this.$refs.upload.click();
      }
    },
    upload(file, fileList) {
      console.log(file);
      const formData = new FormData();
      formData.append("file", file.raw);
      const loading = this.$loading({
        lock: true,
        text: "导入中，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      getTreeByExcel(formData)
        .then((res) => {
          console.log(res);
          if (res.code === 200) {
            this.$modal.msgSuccess("导入成功");
            this.g6Tree = res.data;
            this.targetData = res.data;

            this.g6CmpData = res.data;
            this.importFlag = false;
          } else {
            this.$modal.msgError("导入失败，请修改后重新导入");
          }
        })
        .catch((res) => {
          this.$modal.msgError("导入失败，请重新导入");
        })
        .finally(() => {
          loading.close();
        });
    },

    // 历史导入弹窗 or 暂存导入弹窗
    importByHistoryOrTmp(type) {
      if (type === 1) {
        (this.dialogTitle = "历史指标体系导入"), (this.btnType = "history");
      } else if (type === 2) {
        (this.dialogTitle = "暂存模型导入"), (this.btnType = "tmp");
      }
      if (!this.importFlag) {
        this.$confirm("当前编辑区内容尚未保存，是否继续导入", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 清空
          this.importDialog = true;
          this.getHistoryList();
        });
      } else {
        // 清空
        this.importDialog = true;
        this.getHistoryList();
      }
    },
    searchBtn() {
      this.historyCurrPage = 1;
      this.getHistoryList();
    },
    // 导入弹窗的确认按钮
    commitImport() {
      const loading = this.$loading({
        lock: true,
        text: "导入中，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (this.btnType === "history") {
        queryNewById({ id: this.selectHistoryId }).then((res) => {
          console.log(res);
          if (res.code === 200) {
            this.g6Tree = res.data;
            this.targetData = res.data;
            this.g6CmpData = res.data;
            this.form.name = "";
            this.form.type = "";
            this.form.content = "";
            this.historyCurrPage = 1;
            this.importFlag = false;
            this.handleClose();
            this.$modal.msgSuccess("导入成功");
          }
        });
      } else {
        queryById({ id: this.selectHistoryId }).then((res) => {
          console.log(res);
          if (res.code === 200) {
            this.g6Tree = res.data.tree;
            this.targetData = this.g6Tree;
            this.g6CmpData = this.g6Tree;
            this.form.name = res.data.name;
            this.form.type = res.data.type;
            this.form.content = res.data.content;
            // 后续调编辑接口需要id
            this.editId = res.data.id;
            this.historyCurrPage = 1;
            this.importFlag = false;
            this.handleClose();
            this.$modal.msgSuccess("导入成功");
          }
        });
      }
      loading.close();
    },
    changeHistoryPage(e) {
      this.historyCurrPage = e;
      this.getHistoryList();
    },
    getHistoryList() {
      this.historyListLoading = true;
      getHistoryList({
        status: this.btnType === "history" ? 2 : 1,
        pageNo: this.historyCurrPage,
        pageSize: 10,
        startTime: this.formInline.createTime
          ? this.formInline.createTime[0]
          : "",
        endTime: this.formInline.createTime
          ? this.formInline.createTime[1]
          : "",
        type: this.formInline.type,
        name: this.formInline.name,
      })
        .then((res) => {
          if (res.code === 200) {
            this.historyList = res.data.records;
            this.historyTotal = res.data.total;
          }
        })
        .finally(() => {
          this.historyListLoading = false;
        });
    },
    handleClose() {
      console.log(55555555555);
      this.selectHistoryId = "";
      this.importDialog = false;
      this.$refs.historyForm.resetFields();
    },
    rowClick(val) {
      this.selectHistoryId = val.id;
    },
    uuid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23];
      var uuid = s.join("");
      return uuid;

    },
    // 新建
    newSystem() {
      if (!this.importFlag) {
        this.$confirm("当前编辑区内容尚未保存，是否继续导入", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.g6Tree = {
            code: null,
            id: this.uuid(),
            isBottom: null,
            isId: null,
            label: "xx指标体系",
            level: null,
            num: "0",
            pid: null,
            size: [120, 50],
            sort: null,
            children: [],
          };
          this.targetData = this.g6Tree;
          this.g6CmpData = this.g6Tree;
          this.importFlag = false;
          console.log(this.g6Tree,'ttttttt')
        });
      } else {
        this.g6Tree = {
          code: null,
          id: this.uuid(),
          isBottom: null,
          isId: null,
          label: "xx指标体系",
          level: null,
          num: "0",
          pid: null,
          size: [120, 50],
          sort: null,
          children: [],
        };
        this.targetData = this.g6Tree;
        this.g6CmpData = this.g6Tree;
        this.importFlag = false;
      }
    },
    // 下载模板
    downloadTemplet() {
      downloadTemp();
    },
    // 体系暂存/发布
    saveBbtnClick(status) {
      this.$refs.addForm.validate((valid) => {
        console.log(valid);
        if (!valid) {
          return;
        }
        if (!this.g6Tree || Object.keys(this.g6Tree).length === 0) {
          return this.$modal.msgWarning("请先创建或导入指标体系");
        }
        const loading = this.$loading({
          lock: true,
          text: status === 1 ? "暂存中，请稍后" : "发布中，请稍后",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        if (this.btnType === "tmp") {
          // 需调编辑接口
          console.log(editSystem);
          console.log(typeof editSystem);
          editSystem({
            name: this.form.name,
            type: this.form.type,
            content: this.form.content,
            tree: this.g6Tree,
            id: this.editId,
            status,
          }).then((res) => {
            console.log(res);
            if (res.code === 200) {
              this.$modal.msgSuccess("操作成功");
              this.importFlag = true;
              this.currentId = res.data;
              if(status === 1){
                // this.clearPage();
              }else{
                this.clearPage();

              }
            }
          });
        } else {
          // 调新增接口
          addSystem({
            name: this.form.name,
            type: this.form.type,
            content: this.form.content,
            tree: this.g6Tree,
            status,
          }).then((res) => {
            if (res.code === 200) {
              this.$modal.msgSuccess("操作成功");
              this.editId = res.data;
            }
          });
        }
        if (status === 1) {
          this.btnType === "tmp";
          this.importFlag = false;
        } else {
          this.clearPage();
          this.importFlag = true;
        }
        loading.close();
      });
    },
    clearPage() {
      this.g6Tree = {};
      this.g6CmpData = {};
      this.form = {
        name: "",
        type: null,
        content: "",
      };
      this.editId = 0;
    },

    updateG6Tree(tree) {
      // this.g6Tree = tree;
      // this.targetData = tree;
      // this.g6CmpData = JSON.parse(JSON.stringify( tree ));
      // this.dataBranchChange(tree.id, [this.g6Tree]);
      this.bigTree(tree, [this.g6Tree], '')

    },
    addG6Tree(tree){
      // console.log(tree, 'add');
      // this.g6CmpData = JSON.parse(JSON.stringify( tree ));
      // this.dataBranchChange(tree.id, [this.g6Tree], 'add');
      this.bigTree(tree, [this.g6Tree], 'add')
    },
    deleteTree(tree){
      // this.g6CmpData = JSON.parse(JSON.stringify( tree ));
      // this.dataBranchChange(tree.id, [this.g6Tree], 'delete');
      this.bigTree(tree, [this.g6Tree], 'delete')

    },
    bigTree(tree, all, status){
      if(status == 'delete'){
        const aim = this.lookupSearch(tree.pid, all);
        const i = aim.children.findIndex(item => item.id == tree.id);
        if(i != -1){
          aim.children.splice(i, 1)
        }
      }else if(status == 'add'){
        const aim = this.lookupSearch(tree.pid, all);
        // tree.pid = aim.id;
        // console.log('新增子结点', tree, '父节点', aim);
        if(!aim.children){
          aim.children = []
        }
        aim.children.push(tree)
        this.g6CmpData = aim
      }else{
        const aim = this.lookupSearch(tree.id, all)
        aim.label = tree.label;
        aim.num = tree.num;
        aim.size = tree.size;
        tree.children.forEach((branch,j) => {
          aim.children[j].num =tree.children[j].num
          aim.children[j].label = tree.children[j].label
          aim.children[j].size = tree.children[j].size
        })
        this.g6CmpData = aim
      }
    },
    lookupSearch(id, all){
      let result;
      for(var i=0; i<all.length; i++){
        let item = all[i];
        if( item.id && item.id == id){
          result = item
          return result;
        }else if(item.children && item.children.length>0){
          result = this.lookupSearch( id, item.children)
          if(result){
            return result;
          }
        }
      }
      return result;
    },
    // 图表改变返回给树结构
    dataBranchChange(id, all, status){
      for(var i=0; i<all.length; i++){
        let item = all[i];
        if( item.id && item.id == id){
          if(status == 'delete'){
            console.log(item,'item')
            item.children.forEach((branch,j) => {
              console.log(this.g6CmpData,'g6CmpData')
              const tt = this.g6CmpData.children.findIndex(pp => pp.id == branch.id )
              if(tt == -1){
                item.children.splice(j, 1)
              }
            })
            // alert('delete')
            // item.children = JSON.parse(JSON.stringify(this.branch.children))
            // console.log(this.pp);
          }else if(status == 'add'){
            this.g6CmpData.children.forEach((branch,j) => {
              const tt = item.children.findIndex(pp => pp.id == branch.id )
              if(tt == -1){
                item.children.push(branch)
              }
            })
          }else{
            item.children.forEach((branch,j) => {
              item.children[j].num = this.g6CmpData.children[j].num
              item.children[j].label = this.g6CmpData.children[j].label
              item.children[j].size = this.g6CmpData.children[j].size
            })
          }
          return
        }else if(item.children && item.children.length>0){
          this.dataBranchChange( id, item.children, status)
        }
      }
    },
  },
  created() {},
  mounted() {
    const id = this.$route.query.id;
    if (id) {
      queryById({ id }).then((res) => {
        // console.log(res);
        if (res.code === 200) {
          this.g6Tree = res.data.tree;
          this.targetData = this.g6Tree;
          this.g6CmpData = this.g6Tree;
          this.form.name = res.data.name;
          this.form.type = res.data.type;
          this.form.content = res.data.content;
          // 后续调编辑接口需要id
          this.editId = res.data.id;
          this.importFlag = false;
        }
      });
      this.btnType = "tmp"; // 调编辑接口
    }
  },
};
</script>
<style lang="scss" scoped>
.box-container {
  height: 100%;
  .left-tree,
  .right-box {
    border-radius: 10px;
    background-color: #fff;
  }
  .left-tree {
    width: calc(18.5% - 10px);
    height: 100%;
    margin-right: 10px;
    padding: 10px;
  }
  .right-box {
    width: 81.5%;
    height: 100%;
    padding: 0 20px;
    .right-top {
      height: 50px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #e4e8f1;
      .pageTitle {
        font-size: 18px;
        font-family: Alibaba PuHuiTi;
        font-weight: 500;
        color: #3771f5;
        line-height: 63px;
      }
      .flexAlign {
        display: flex;
        align-items: center;
        img {
          display: block;
          margin-right: 5px;
        }
        span {
          display: flex;
          align-items: center;
        }
      }
      ::v-deep .el-button.download-btn {
        background: #f0f4fc;
        border: 1px solid #e1e5f4;
        border-radius: 5px;
        color: #000;
        &:hover {
          background: #fff;
        }
      }
    }
    .right-middle {
      height: calc(100% - 310px);

      .graph {
        width: 100%;
        height: 100%;
        border: 1px solid #91b2cc;
        border-radius: 4px;
      }
    }
    .right-bottom {
      height: 200px;
      ::v-deep .el-form {
        margin-top: 10px;
      }
      ::v-deep .el-input {
        width: 300px;
      }
      ::v-deep .el-textarea {
        width: 800px;
      }
    }
    .right-footer {
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      .save-btn {
        // top: 50%;
        // left: 50%;
        // transform: translate(-50%, -50%);
      }
    }
  }
}
.upload {
  width: 360px;
  margin: 0 auto;
}
::v-deep .el-table__header-wrapper th {
  background-color: rgba(54, 112, 245, 0.05);
  color: #65769d;
  font-size: 14px;
}
</style>
